package com.xux.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xux.dao.OrderSlicDao;
import com.xux.model.po.OrderSlic;
import com.xux.service.ICanalDataProcess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 订单切片数据监听.
 *
 * @author xux
 * @date 2022/12/2
 */
@Slf4j
@Component
public class OrderSlicCanalDataProcess implements ICanalDataProcess {
    @Autowired
    private OrderSlicDao orderSlicDao;

    @Override
    public boolean support(final String table) {
        return "op_order_slic".equals(table);
    }

    @Override
    public void processInsert(final JSONArray jsonArray) {
        log.debug("[op_order_slic]表数据新增:{}", jsonArray);
        for (Object obj:jsonArray){
            JSONObject jsonObject = (JSONObject) obj;
            OrderSlic orderSlic = toOrderSlic(jsonObject);
            orderSlicDao.save(orderSlic);
        }
    }

    @Override
    public void processUpdate(final JSONArray jsonArray) {
        log.debug("[op_order_slic]表数据更新:{}", jsonArray);
        for (Object obj:jsonArray){
            JSONObject jsonObject = (JSONObject) obj;
            OrderSlic orderSlic = toOrderSlic(jsonObject);
            Long id = orderSlic.getId();
            Optional.ofNullable(orderSlicDao.findById(id)).ifPresent(orderSlic1 -> orderSlicDao.save(orderSlic));
        }
    }

    @Override
    public void processDelete(final JSONArray jsonArray) {
        log.debug("[op_order_slic]表数据删除:{}", jsonArray);
        for (Object obj:jsonArray){
            JSONObject jsonObject = (JSONObject) obj;
            OrderSlic orderSlic = toOrderSlic(jsonObject);
            Long id = orderSlic.getId();
            Optional.ofNullable(orderSlicDao.findById(id)).ifPresent(orderSlic1 -> orderSlicDao.deleteById(id));
        }
    }

    private OrderSlic toOrderSlic(JSONObject jsonObject){
        OrderSlic orderSlic = new OrderSlic();
        orderSlic.setId(jsonObject.getLong("id"));
        orderSlic.setShopId(jsonObject.getLong("shop_id"));
        orderSlic.setOrdered(jsonObject.getStr("ordered"));
        orderSlic.setSlicDate(jsonObject.getDate("slic_date"));
        orderSlic.setInventory(jsonObject.getLong("inventory"));
        orderSlic.setOrderNum(jsonObject.getInt("order_num"));
        orderSlic.setSkuId(jsonObject.getLong("sku_id"));
        orderSlic.setPrice(jsonObject.getBigDecimal("price"));
        orderSlic.setShopName(jsonObject.getStr("shop_name"));
        orderSlic.setOuterId(jsonObject.getStr("outer_id"));
        orderSlic.setActivityInventory(jsonObject.getLong("activity_inventory"));
        orderSlic.setReserveQuantity(jsonObject.getLong("reserve_quantity"));
        //orderSlic.setActivityStatus(jsonObject.getInt());
        //orderSlic.setActivityReason();
        //orderSlic.setPlatFormType();
        return orderSlic;
    }

}
